package com.seadragon.app.ksr.model;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

public class Pagination {
	private int currentPage;
	private int totalDocs;
	private int docsPerPage;
	private String baseUrl;
	
	public int getCurrentPage() {
		return currentPage;
	}

	public int getTotalDocs() {
		return totalDocs;
	}

	public int getDocsPerPage() {
		return docsPerPage;
	}

	public Pagination(int currentPage,int totalDocs, int docsPerPage, String url, String queryString){
		this.currentPage = currentPage;
		this.totalDocs = totalDocs;
		this.docsPerPage = docsPerPage;
		this.baseUrl = setBaseUrl(url,queryString);
	}
	
	private String setBaseUrl(String url, String queryString) {
		if (StringUtils.isNotEmpty(url)&&StringUtils.isNotEmpty(queryString)){
			//take out the "currentPage=x" from queryString and append "currentPage=" to the queryString
//			queryString.replaceAll("[&]*currentPage=\\d*", "");
			queryString=StringUtils.removePattern(queryString, "[&]*currentPage=\\d*");
			//remove leading "&"
			queryString=StringUtils.removeStart(queryString, "&");
			return url+"?"+queryString+((StringUtils.isNotEmpty(queryString))?"&":"")+"currentPage=";
			
		} else if (StringUtils.isNotEmpty(url)){
			return url;
		}
		return null;
	}
	
	public String getBaseUrl(){
		return this.baseUrl;
	}

	public String getPrevUrl(){
		if (StringUtils.isNotEmpty(this.baseUrl)&&currentPage>1){
			return this.baseUrl+(currentPage-1);
		} else {
			return null;
		}
	}
	public String getNextUrl(){
		if (StringUtils.isNotEmpty(this.baseUrl)&&currentPage<getTotalPages()){
			return this.baseUrl+(currentPage+1);
		} else {
			return null;
		}
	}
	public int getTotalPages(){
		if (this.docsPerPage>0 && this.totalDocs>0){
			return (int)Math.ceil((double)this.totalDocs/(double)this.docsPerPage);
		}
		return 1;
	}
	public List<String> getPageNumbers(){
		List<String> pn = new ArrayList<>();
		if (getTotalPages()<8){
			for (int i = 1; i <= getTotalPages(); i++) {
				pn.add(""+i);
			}
		} else {
			for (int i = 1; i <= getTotalPages(); i++) {
				if (i==1||i==getTotalPages()||(i==getCurrentPage()-1)||(i==getCurrentPage())||(i==getCurrentPage()+1)){
					pn.add(""+i);
				} else if ((i==getCurrentPage()-2)||(i==getCurrentPage()+2)){
					pn.add("...");
				}
			}
			
		}
		return pn;
	}
}
